#include "BasicBlock.h"
#include "Constant.h"
#include "Function.h"
#include "IRBuilder.h"
#include "Module.h"
#include "Type.h"

#include <iostream>
#include <memory>

#ifdef DEBUG  // 用于调试信息,大家可以在编译过程中通过" -DDEBUG"来开启这一选项
#define DEBUG_OUTPUT std::cout << __LINE__ << std::endl;  // 输出行号的简单示例
#else
#define DEBUG_OUTPUT
#endif

#define CONST_INT(num) \
    ConstantInt::get(num, module)

#define CONST_FP(num) \
    ConstantFP::get(num, module) // 得到常数值的表示,方便后面多次用到

int main() {
  auto module = new Module("Cminus code");  // module name是什么无关紧要
  auto builder = new IRBuilder(nullptr, module);
  Type *Int32Type = Type::get_int32_type(module);

// main函数
  auto mainFun = Function::create(FunctionType::get(Int32Type, {}),
                                  "main", module);
  auto bb = BasicBlock::create(module, "entry", mainFun);
  builder->set_insert_point(bb);
  auto aAlloca = builder->create_alloca(Int32Type);
  auto iAlloca = builder->create_alloca(Int32Type);
  builder->create_store(CONST_INT(10),aAlloca);
  builder->create_store(CONST_INT(0),iAlloca);
  
  auto cmpBB = BasicBlock::create(module, "cmpBB", mainFun);    // cmp分支
  auto trueBB = BasicBlock::create(module, "trueBB", mainFun);    // true分支
  auto falseBB = BasicBlock::create(module, "falseBB",mainFun);  // false分支
  builder->create_br(cmpBB);//进入cmp分支
  builder->set_insert_point(cmpBB);//cmpBB分支开始
  auto icmp = builder->create_icmp_lt(iAlloca, CONST_INT(10));  // i和10的比较,注意ICMPLT
  auto br = builder->create_cond_br(icmp, trueBB, falseBB);  // 条件BR
  DEBUG_OUTPUT // 我调试的时候故意留下来的,以醒目地提醒你这个调试用的宏定义方法
  builder->set_insert_point(trueBB);  // if true; 分支的开始需要SetInsertPoint设置
  auto add=builder->create_iadd(CONST_INT(1),iAlloca);
  builder->create_store(add,iAlloca);//i=i+1
  auto addd=builder->create_iadd(iAlloca,aAlloca);
  builder->create_store(addd,aAlloca);//a=a+i
  builder->create_br(cmpBB);//返回cmpBB，构成while循环
  builder->set_insert_point(falseBB);  // if false
  auto ret=builder->create_load(aAlloca);
  builder->create_ret(ret);//返回a

  std::cout << module->print();
  delete module;
  return 0;
}